<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑公文' : '新增公文' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="公文标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公文标题" />
        </el-form-item>
        <el-form-item label="公文类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择公文类型" style="width: 100%">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发文单位" prop="issuer">
          <el-input v-model="form.issuer" placeholder="请输入发文单位" />
        </el-form-item>
        <el-form-item label="发文日期" prop="issueDate">
          <el-date-picker
            v-model="form.issueDate"
            type="datetime"
            placeholder="选择发文日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgencyLevel">
          <el-select v-model="form.urgencyLevel" placeholder="请选择紧急程度" style="width: 100%">
            <el-option v-for="item in urgencyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="密级" prop="securityLevel">
          <el-select v-model="form.securityLevel" placeholder="请选择密级" style="width: 100%">
            <el-option v-for="item in securityOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批流程" prop="approvalFlowId">
          <el-select v-model="form.approvalFlowId" placeholder="请选择审批流程" style="width: 100%">
            <el-option v-for="item in flowOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="公文内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="15"
            placeholder="请输入公文内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            :action="uploadUrl"
            :headers="headers"
            :data="uploadData"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">可上传任意类型文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="抄送人">
          <el-select
            v-model="form.ccUserIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词搜索"
            :remote-method="remoteSearchUsers"
            :loading="loading"
            style="width: 100%"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">保存</el-button>
          <el-button @click="submitForm('form', true)" v-if="!isEdit">保存并提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getDocumentDetail, createDocument, updateDocument, submitDocument } from '@/api/document'
import { getToken } from '@/utils/auth'
import { searchUsers } from '@/api/user'

export default {
  name: 'DocumentEdit',
  data() {
    return {
      isEdit: false,
      loading: false,
      form: {
        id: undefined,
        title: '',
        type: 1,
        issuer: '',
        issueDate: new Date(),
        content: '',
        urgencyLevel: 1,
        securityLevel: 1,
        approvalFlowId: undefined,
        attachmentIds: [],
        ccUserIds: []
      },
      rules: {
        title: [{ required: true, message: '请输入公文标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择公文类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入公文内容', trigger: 'blur' }],
        approvalFlowId: [{ required: true, message: '请选择审批流程', trigger: 'change' }]
      },
      typeOptions: [
        { value: 1, label: '通知' },
        { value: 2, label: '请示' },
        { value: 3, label: '报告' },
        { value: 4, label: '决定' },
        { value: 5, label: '其他' }
      ],
      urgencyOptions: [
        { value: 1, label: '普通' },
        { value: 2, label: '紧急' },
        { value: 3, label: '特急' }
      ],
      securityOptions: [
        { value: 1, label: '普通' },
        { value: 2, label: '秘密' },
        { value: 3, label: '机密' },
        { value: 4, label: '绝密' }
      ],
      flowOptions: [],
      userOptions: [],
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/documents/attachment',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadData: {
        uploaderId: this.$store.getters.userId,
        uploaderName: this.$store.getters.name
      }
    }
  },
  created() {
    const id = this.$route.params.id
    if (id) {
      this.isEdit = true
      this.getDetail(id)
    }
    this.getFlowOptions()
  },
  methods: {
    getDetail(id) {
      getDocumentDetail(id).then(response => {
        this.form = response.data
        // 处理附件列表
        if (this.form.attachments && this.form.attachments.length > 0) {
          this.fileList = this.form.attachments.map(item => {
            return {
              name: item.name,
              url: item.path,
              id: item.id
            }
          })
          this.form.attachmentIds = this.form.attachments.map(item => item.id)
        }
      })
    },
    getFlowOptions() {
      // 获取审批流程选项
      // 这里应该调用获取审批流程列表的API
      this.flowOptions = [
        { value: 1, label: '部门主管审批' },
        { value: 2, label: '总经理审批' },
        { value: 3, label: '三级审批流程' }
      ]
    },
    remoteSearchUsers(query) {
      if (query !== '') {
        this.loading = true
        searchUsers({ keyword: query }).then(response => {
          this.userOptions = response.data.map(item => {
            return { value: item.id, label: item.name + ' (' + item.username + ')' }
          })
          this.loading = false
        })
      } else {
        this.userOptions = []
      }
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.attachmentIds.push(response.data)
        this.$message.success('上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleRemove(file, fileList) {
      if (file.id) {
        const index = this.form.attachmentIds.indexOf(file.id)
        if (index !== -1) {
          this.form.attachmentIds.splice(index, 1)
        }
      }
    },
    submitForm(formName, submit = false) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const method = this.isEdit ? updateDocument : createDocument
          method(this.form).then(response => {
            this.$message.success('保存成功')
            if (submit && !this.isEdit) {
              // 保存并提交
              submitDocument(response.data).then(() => {
                this.$message.success('提交成功')
                this.$router.push('/document')
              })
            } else {
              this.$router.push('/document')
            }
          })
        } else {
          return false
        }
      })
    },
    cancel() {
      this.$router.push('/document')
    }
  }
}
</script> 